<?php

namespace App\Http\Controllers;

use App\Models\Floor;
use App\Models\Room;
use Illuminate\Http\Request;

class RoomController extends Controller
{
    /**
     * @return void
     */
    public function roomAdd(Request $request)
    {
        $val = $request->validate(
            [
                "f_id" => 'required',
                'name' => 'required',
                'id' => 'nullable'
            ]
        );
        if (!empty($val['id'])) {
            $data = Room::find($val['id']);
            $data->name = $val['name'];
            $data->save();
        } else {
            $data = Room::create($val);
        }
        $responseJson = [
            'code' => 200,
            'message' => '',
            'data' => $data->id
        ];
        return Response()->json($responseJson);
    }

    /**
     * @return void
     */
    public function roomList(Request $request)
    {
        $val = $request->validate(
            [
                "keyword" => 'nullable',
                "f_id" => 'nullable',
                'page' => 'nullable|integer',
                'pageSize' => 'nullable|integer',
            ]
        );
        $pageSize = $val['pageSize'] ?? 20; // 默认每页20条记录
        // 创建查询构建器
        $query = Room::with(['floor']);
        if (!empty($val['keyword'])) {
            $query->where('name', 'LIKE', '%' . $val['keyword'] . '%');
        }
        if (!empty($val['f_id'])) {
            $query->where('f_id', $val['f_id']);
        }
        $rooms = $query->paginate($pageSize);;
        $data = [
            'page' => $rooms->currentPage(),
            'pageSize' => intval($rooms->perPage()),
            'rows' => $rooms->items(),
            'total' => $rooms->total(),
        ];
        $responseJson = [
            'code' => 200,
            'message' => '',
            'data' => $data
        ];
        return Response()->json($responseJson);
    }

    /***
     * @return void
     */
    public function roomDel($ids)
    {
        if (strpos($ids, ',') !== false) {
            $numbers = explode(',', $ids);
            foreach ($numbers as $num) {
                $room = Room::findOrFail($num);
                $room->delete();
            }
        } else {
            $room = Room::findOrFail($ids);
            $room->delete();
        }
        $responseJson = [
            'code' => 200,
            'message' => '成功删除',
        ];
        return response()->json($responseJson);
    }
}
